<?php


$dir = dirname(__FILE__);

require_once("$dir/Communicator.php");
require_once("$dir/Database.php");
require_once("$dir/Session.php");
require_once("$dir/Room.php");
require_once("$dir/Update.php");
require_once("$dir/Message.php");

class User{
	private $id;
	private $room;
	private $session;
	
	private $db;
	private $cmm;
	private $ss;
		
	//REMOVER
	private $openedSessions; //all sessions currently opened with this user
	private $openedGroupsRooms; //all rooms currently opened whose group contains this user as a member
	private $openedGroupsAsRooms; //all groups currently opened as rooms that contains this user as a member
	private $groups; //all groups with this user (owner or not)
	private $groupsIds;
	//private $groupRooms; //save the results computed
	private $ownedGroups;

	public function __construct($id=null){
		$this->id = $id;
		$this->session = null;

		$this->db = new Database;
		$this->cmm = new Communicator;
		$this->ss = new Session;
	}

	public function getId(){
		return $this->id;
	}

	public function getRoom(){
		return $this->room;
	}

	public function getSession(){
		return $this->session;
	}

	public function setId($id){
		$this->id = $id;
	}

	public function setSession($session){
		$this->session = $session;
	}

	public function setRoom($room){
		if(is_numeric($room)) $room = new Room($room);

		$this->room = $room;
	}

	//public function resolveGroupRooms($json = false){
	public function resolveGroupRooms(){
		$this->resolveGroups();
		$this->resolveGroupsIds();
		$this->resolveOpenedSessions();
		$this->resolveOpenedGroupsRooms();
		$this->resolveOwnedGroups();

		$json = array('groups'=>$this->groups,'ownedGroups'=>$this->ownedGroups,'groupsIds'=>$this->groupsIds,'openedGroupsRooms'=>$this->openedGroupsRooms,'openedGroupsAsRooms'=>$this->openedGroupsAsRooms,'roomSessions'=>$this->openedSessions);
		
		$json = json_encode($json);

		$json = str_replace('"', '\\"', $json);
		$json = str_replace("'", "\\'", $json);//(json_encode($json));

		echo $json;
	}

	private function resolveGroups(){
		$data = $this->cmm->getData('me',array('groups'));
		
		$groups = $data['groups']['data'];

		$this->groups = $groups;
	}	

	private function resolveGroupsIds(){
		$groupsIds = array();
		$groups = array();

		foreach($this->groups as $group){
			$id = $group['id'];
			$groups['group_'.$id] = $group;
			$groupsIds['group_'.$id] = $id;
		}

		$this->groups = $groups;
		$this->groupsIds = $groupsIds;
	}

	private function resolveOpenedSessions(){
		$userId = $this->id;
		//file_put_contents('teste', "SELECT su.session, su.room FROM session_update su WHERE su.user = '$userId'");
		$res = $this->db->execute("SELECT su.session, su.room FROM session_update su WHERE su.user = '$userId'");
		$openedSessions= array();
		while($session = mysql_fetch_array($res,MYSQL_ASSOC)){ //Find what groups are opened as rooms	
			$sessionId = $session['session'];
			$roomId = $session['room'];

			$openedSessions['session_'.$sessionId] = $roomId;
			$openedSessions['room_'.$roomId] = $sessionId;
		}

		$this->openedSessions = $openedSessions;
	}

	private function resolveOpenedGroupsRooms(){
		$groupsId = implode(',',$this->groupsIds);
		
		$query = 'SELECT * FROM room r WHERE end IS NULL';
		if($groupsId != '') $query .= " AND r.group IN ($groupsId)";

		$res = $this->db->execute($query);

		$openedGroupsAsRooms = $openedGroupsRooms = array();
		
		while($room = mysql_fetch_array($res,MYSQL_ASSOC)){ //Find what groups are opened as rooms				
			$roomId = $room['id'];
			$groupId = $room['group'];

			$openedGroupsRooms['room_'.$roomId] = 'group_'.$groupId;
			$openedGroupsAsRooms['group_'.$groupId] = 'room_'.$roomId;
		}

		$this->openedGroupsRooms = $openedGroupsRooms;
		$this->openedGroupsAsRooms = $openedGroupsAsRooms;
	}

	private function resolveOwnedGroups(){
		$ownedGroups = array();

		foreach($this->groups as $group){ //Find what are the groups the user owns and what are the ones he's in.
			$groupId = $group['id'];
			
			if(isset($group['administrator'])){ //se é o administrador e esse grupo não possui uma sala aberta
				//if(!isset($this->openedGroupsAsRooms['group_'.$groupId])) $createRoom[] = 'group_'.$groupId;
				$ownedGroups[] = 'group_'.$groupId;
			}
		}

		$this->ownedGroups = $ownedGroups;
	}	
/*
	private function retrieveCreateRoomOptions(){
		$createRoom = array();
		
		$ownedGroups = array();

		foreach($this->groups as $group){ //Find what are the groups the user owns and what are the ones he's in.
			$groupId = $group['id'];
			
			if(isset($group['administrator'])){ //se é o administrador e esse grupo não possui uma sala aberta
				//if(!isset($this->openedGroupsAsRooms['group_'.$groupId])) $createRoom[] = 'group_'.$groupId;
				$ownedGroups[] = 'group_'.$groupId;
			}
		}

		$this->ownedGroups = $ownedGroups;
		return $ownedGroups;
		//return $createRoom;
	}

	private function retrieveEnterRoomOptions(){
		$enterRoom = array();
	
		foreach($this->openedGroupsRooms as $roomKey => $groupKey){//grupos que key = room_#, value = groupId
			//echo $groupKey;
			//if(!isset($this->openedSessions[$roomKey])){ //se a room está aberta, mas o usuário não possui uma sessão aberta nela
			if(!isset($this->groups[$groupKey]['administrator'])){
				$enterRoom[] = $groupKey;
			}
		}

		return $enterRoom;		
	}

	public function placeOpenedRooms(){
		$html = '';
		$openedRooms = $this->retrieveEnterRoomOptions();
		
		foreach($openedRooms as $groupKey){
			$group = $this->groups[$groupKey];
			$roomKey = $this->openedGroupsAsRooms[$groupKey];

			$html .= "<div class='openedRoom item' onClick='enterRoom(event)' DATA-KEY='$roomKey'><p class='name'>".$group['name']."</p></div>";
		}

		echo $html;
	}
	
	public function placeOwnedGroups(){
		$html = '';
		$ownedGroups = $this->retrieveCreateRoomOptions();
		
		foreach($ownedGroups as $groupKey){
			$group = $this->groups[$groupKey];

			$html .= "<div class='ownedGroup item' onClick='openRoom(event)' DATA-KEY='$groupKey'><p class='name'>".$group['name']."</p></div>";
		}

		echo $html;
	}
	
	private function createGroupRoomsHtml($input){
		if(isset($input['openedRooms'])){
			$html = '<section id="openedRooms"><p class="title">Salas abertas</p>';
			$openedRooms = $input['openedRooms'];
			
			foreach($openedRooms as $groupKey){
				$group = $this->groups[$groupKey];
				$roomKey = $this->openedGroupsAsRooms[$groupKey];

				$html .= "<div class='openedRoom item' onClick='enterRoom(event)' DATA-KEY='$roomKey'><p class='name'>".$group['name']."</p></div>";
			}

			$html .= '</section>';

			echo $html;
		}

		if(isset($input['ownedGroups'])){
			$html = '<section id="ownedGroups"><p class="title">Abrir uma sala</p>';
			$ownedGroups = $input['ownedGroups'];
			
			foreach($ownedGroups as $groupKey){
				$group = $this->groups[$groupKey];

				$html .= "<div class='ownedGroup item' onClick='openRoom(event)' DATA-KEY='$groupKey'><p class='name'>".$group['name']."</p></div>";
			}

			$html .= '</section>';

			echo $html;
		}
	}*/

	public function enterRoom($params){
		$this->ss = new Session();

		$this->id = $this->ss->getData('id');
		$this->room = new Room($params['room']);
		
		$this->startSession();
	}

	public function startSession($check=true){
		$allowed = true;

		if($check){
			$this->db->execute("SELECT * FROM room r INNER JOIN session s ON s.room = r.id WHERE r.id = {$this->room->getId()} AND s.user = '{$this->id}' AND s.end IS NULL");	
			if($this->db->getNumberOfRows() != 0) $allowed = false;
		} 

		if($allowed){
			$this->db->execute("INSERT INTO session (user, room, start) VALUES ('{$this->id}', {$this->room->getId()}, NOW())");
			$sessionId = $this->db->getInsertedId();
			//$fh = new FileHandler($this->room->getPath().'user/');
			//$fh->createFile("user/{$this->id}");
			//$fh->createFile("user/{$this->id}");
			$roomId = $this->room->getId();
			
			$params = array('user'=>$this->id,'session'=>array($sessionId,'string'),'room'=>$roomId,'content'=>'','last_activity'=>array('NOW()','function'));
			$this->db->execute($this->db->getInsertQuery('session_update',$params));

			$data = array('access'=>1);
			$update = new Update($this, $data);
			$update->addAccess();

			$this->ss->setData('session_room_'.$roomId,$sessionId);

			echo json_encode($roomId);
		}
	}

	public function leaveRoom($params=null){
		if($params != null){
			$this->ss = new Session();
			$this->id = $this->ss->getData('id');
			
			if(isset($params['room'])) $this->room = new Room($params['room']);				
			if(isset($params['session'])) $this->session = $params['session'];
		}		

		$roomId = $this->room->getId();

		if(is_numeric($this->session)){
			$firstCondition = "id = {$this->session}";
			$seconCondition = "session = {$this->session}";	
		} 
		else $firstCondition = $seconCondition = "room = $roomId AND user = '{$this->id}'";

		$query = "UPDATE session SET end = NOW() WHERE $firstCondition AND end IS NULL";
		
		$this->db->execute($query);

		if($this->db->getAffectedRows() > 0){
			$data = array('access'=>0);

			$update = new Update($this, $data);
			$update->addAccess();

			//$fh = new FileHandler($this->room->getPath());
			//$fh->deleteFile("user/{$this->id}");

			$query = "DELETE FROM session_update WHERE $seconCondition";
			$this->db->execute($query);

			$this->ss->removeData('session_room_'.$roomId); //remove the reference to this user's session from the session variable
			
			echo 1;
		}
	}

	public function openRoom($params){
		$this->ss = new Session();

		$this->id = $this->ss->getData('id');
		$groupId = $params['group'];
		
		$this->room = new Room();
		$this->room->setGroup($groupId);
		$res = $this->room->open();
		
		if($res) $this->startSession(false);
		else echo json_encode(0);
	}

	public function closeRoom($params){
		$this->ss = new Session();

		$this->id = $this->ss->getData('id');

		$this->room = new Room($params['room']);
		$this->room->close();
	}

	public function sendStatus($params){
		$roomId = $params['room'];
		$this->ss = new Session();

		$this->id = $this->ss->getData('id');
		$this->room = new Room($roomId);
		$this->session = $this->ss->getData('session_room_'.$roomId);

		$update = new Update($this, $params);
		$update->addStatus();
	}

	public function sendMessage($data){
		$this->ss = new Session();
		$roomId = $data['room'];

		$this->id = $this->ss->getData('id');
		$this->room = new Room($roomId);
		$this->session = $this->ss->getData('session_room_'.$roomId);
		
		$hour = date('H') - TIMEZONE_ + $this->ss->getData('timezone');
		$date = date('Y-m-d');
		$time = $hour.':'.date('i:s');
		$datetime = "$date $time";

		$message = new Message();
		$message->setMessage($this,$data['text'],$datetime,$data['parent']);

		$update = new Update($this, $message);
		$updateResponse = $update->addMessage();

		echo json_encode(array($data['counter'],$updateResponse));
	}

	public function getUpdates($params){
		$this->ss = new Session();

		$roomId = $params['room'];
		
		$this->session = $this->ss->getData('session_room_'.$roomId);

		if(!is_numeric($this->session)){
			echo json_encode(0);
			return false;
		}

		$this->id = $this->ss->getData('id');
		$this->room = new Room($roomId);

		$update = new Update($this);
		$update->get();

		/*$fh = new FileHandler($this->room->getPath());

		$response='';
		$content = $fh->getFileContent("user/{$this->id}",true);
		if($content === false) $response = 0; //was disconnected
		else{
			if($content != '')	$response = str_replace("\n",',',$content);		
			 $response = '['.$response.']';
		} 		

		echo $response;*/
	}

	public function away($data){
		echo date('H:i:s');
	}

	public function logout(){
		$this->ss = new Session();
		
		echo $this->ss->end();
	}

}

?>
